package cn.wolfcode.luowowo.search.service;

import cn.wolfcode.luowowo.article.domain.Tourist;
import cn.wolfcode.luowowo.article.service.ITouristService;
import cn.wolfcode.luowowo.search.domain.DestinationTemplate;
import cn.wolfcode.luowowo.search.domain.RouteTemplate;
import cn.wolfcode.luowowo.search.query.DestintionQuery;
import cn.wolfcode.luowowo.search.repository.DestinationTemplateRepository;
import cn.wolfcode.luowowo.search.vo.DestVo;
import cn.wolfcode.luowowo.search.vo.TouristVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class DestinationServiceImpl implements IDestinationSearchService {

    @Autowired
    private DestinationTemplateRepository repository;
    @Autowired
    private ElasticsearchTemplate template;
    @Autowired
    private IRouteSearchService routeSearchService;
    @Reference
    private ITouristService touristService;

    @Override
    public void saveOrUpdate(DestinationTemplate destinationTemplate) {
        repository.save(destinationTemplate);
    }

    @Override
    public DestinationTemplate findDestByName(String keyword) {
        return repository.findByName(keyword);
    }

    @Override
    public List<DestVo> selectDestBYCondition(DestintionQuery qo) {
        Page<RouteTemplate> destList=routeSearchService.selectDest(qo);
        List<RouteTemplate> content = destList.getContent();
        List<DestVo> destVos = new ArrayList<DestVo>();
        ArrayList<Long> longs = new ArrayList<>();
        for (RouteTemplate r:content){
            Long destId = r.getDestId();
            if(longs.contains(destId)){
                continue;
            }
            DestinationTemplate dt = repository.findById(destId).get();
            DestVo destVo = new DestVo();
            destVo.setCoverUrl(dt.getCoverUrl());
            destVo.setName(dt.getName());
            destVo.setId(dt.getId());
            destVo.setInfo(dt.getInfo());
            destVo.setRouteName(dt.getHotRoute());
            ArrayList<TouristVo> tv = new ArrayList<>();
            List<Tourist> tourists = touristService.queryTop5ByDestId(destId);
            for(Tourist t:tourists){
                TouristVo touristVo = new TouristVo();
                BeanUtils.copyProperties(t,touristVo);
                tv.add(touristVo);
            }
            destVo.setTourist(tv);
            destVos.add(destVo);
            longs.add(destId);
        }
        return destVos;
    }
}
